<template>
  <div class="vehicle-detail">
    <van-nav-bar title="车辆详情" left-text="返回"  left-arrow @click-left="router.back()" fixed />


    <div class="image-section">
      <img :src="displayImage" :alt="vehicleInfo?.vehicleName || 'vehicle'" class="vehicle-image" />
      <button class="change-btn" @click="fileInput?.click()">更换图片</button>
      <input ref="fileInput" class="file-input" type="file" accept="image/*" @change="onFileChange" />
    </div>
    <div class="upload-section minimal" v-if="selectedFile">
      <div class="tip">为车辆：{{vehicleInfo?.vehicleName}}更换图片（支持 jpg/png/webp）</div>
      <button class="upload-btn" :disabled="uploading" @click="uploadImage">{{ uploading ? '上传中' : '确认' }}</button>
    </div>
    <div class="info-section" v-if="vehicleInfo">
      <div class="row"><span class="label">名称</span><span class="value">{{ vehicleInfo.vehicleName || '-' }}</span>
      </div>
      <div class="row"><span class="label">VIN</span><span class="value">{{ vehicleInfo.vinNo || '-' }}</span></div>
      <div class="row"><span class="label">型号</span><span class="value">{{ vehicleInfo.modelName ||
        vehicleInfo.vehicleModel || '-' }}</span></div>
      <div class="row"><span class="label">设备号</span><span class="value">{{ vehicleInfo.deviceName || '-' }}</span>
      </div>
    </div>

    <!-- 车辆数据详情 -->
    <div class="details-section" v-if="vehicleInfo">
      <div class="section-title">车辆详情</div>
      <div class="details-grid">
        <div class="detail-item" v-if="vehicleInfo?.totalRideMile">
          <div class="detail-label">总里程</div>
          <div class="detail-value">{{ vehicleInfo.totalRideMile }} km</div>
        </div>
        <div class="detail-item" v-if="vehicleInfo?.maxMileage">
          <div class="detail-label">最大续航里程</div>
          <div class="detail-value">{{ vehicleInfo.maxMileage }} km</div>
        </div>
        <div class="detail-item" v-if="vehicleInfo?.chargeState !== undefined">
          <div class="detail-label">充电状态</div>
          <div class="detail-value">{{ String(vehicleInfo.chargeState) === '1' ? '充电中' : '未充电' }}</div>
        </div>
        <div class="detail-item" v-if="vehicleInfo?.pressure || vehicleInfo?.pressureValue">
          <div class="detail-label">胎压</div>
          <div class="detail-value">{{ vehicleInfo.pressureValue || vehicleInfo.pressure }}</div>
        </div>
        <div class="detail-item" v-if="vehicleInfo?.activationDate">
          <div class="detail-label">激活日期</div>
          <div class="detail-value">{{ vehicleInfo.activationDate }}</div>
        </div>
        <div class="detail-item" v-if="vehicleInfo?.firstBindDate">
          <div class="detail-label">绑定日期</div>
          <div class="detail-value">{{ formatBindDate(vehicleInfo.firstBindDate) }}</div>
        </div>
        <div class="detail-item" v-if="vehicleInfo?.rechargeEndDate">
          <div class="detail-label">保修期至</div>
          <div class="detail-value">{{ vehicleInfo.rechargeEndDate }}</div>
        </div>
        <div class="detail-item" v-if="vehicleInfo?.otaVersion">
          <div class="detail-label">软件版本</div>
          <div class="detail-value">{{ vehicleInfo.otaVersion }}</div>
        </div>
        <div class="detail-item" v-if="vehicleInfo?.greenContribution">
          <div class="detail-label">绿色贡献</div>
          <div class="detail-value">{{ vehicleInfo.greenContribution }} kg</div>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import request from '@/utils/request';
import { useVehicleStore } from '@/stores/vehicle';
import { showSuccessToast, showFailToast } from 'vant';
const router = useRouter();

const route = useRoute();
const vehicleStore = useVehicleStore();

const queryVehicleId = computed(() => route.query.vehicleId);
const queryVinNo = computed(() => route.query.vinNo);

const vehicleInfo = computed(() => {
  const list = vehicleStore.vehicleList || [];
  const id = queryVehicleId.value;
  const vin = queryVinNo.value;
  return (
    list.find(v => v.vehicleId == id) ||
    list.find(v => v.vinNo && v.vinNo == vin) ||
    null
  );
});

const previewImage = ref('');
const displayImage = computed(() => {
  if (previewImage.value) return previewImage.value;
  const v = vehicleInfo.value || {};
  return (
    v.customImage || v.custom_image || v.vehiclePicUrl || v.vehicleScalePicUrl || v.vehicleBackPicUrl || ''
  );
});

const selectedFile = ref(null);
const uploading = ref(false);
const fileInput = ref(null);

const onFileChange = (e) => {
  const file = e.target.files && e.target.files[0];
  selectedFile.value = file || null;
};

const uploadImage = async () => {
  if (!selectedFile.value) { showFailToast('请先选择图片'); return; }
  if (!vehicleInfo.value) {
    showFailToast('未找到当前车辆');
    return;
  }
  uploading.value = true;
  try {
    const form = new FormData();
    form.append('file', selectedFile.value);
    const vehicleId = vehicleInfo.value.vehicleId || vehicleInfo.value.vinNo || vehicleInfo.value.deviceName;
    const resp = await request({
      url: `/api/vehicles/${encodeURIComponent(vehicleId)}/image`,
      method: 'post',
      data: form,
    });
    // 立即本地预览新图片（优先绝对地址）
    const path = resp?.data?.url || resp?.data?.image_url || resp?.data?.image_path || null;
    if (path) previewImage.value = path;
    showSuccessToast('上传成功');
    await vehicleStore.fetchVehicleList?.();
    if (fileInput.value) fileInput.value.value = '';
    selectedFile.value = null;
  } catch (e) {
    const msg = e?.response?.data?.message || e?.message || '上传失败';
    showFailToast(msg);
  } finally {
    uploading.value = false;
  }
};

const formatBindDate = (val) => {
  if (!val) return '-';
  try {
    let d;
    if (typeof val === 'number') {
      d = new Date(val > 1e12 ? val : val * 1000);
    } else {
      d = new Date(val);
    }
    if (isNaN(d.getTime())) return String(val);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
  } catch (e) {
    return String(val);
  }
};
</script>

<style scoped>
.vehicle-detail {
  padding: 16px;
  padding-top: 46px;
}

.header {
  margin-bottom: 12px;
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.subtitle {
  font-size: 12px;
  color: #888;
  margin-top: 4px;
}

.image-section {
  position: relative;
  display: flex;
  justify-content: center;
  margin: 12px 0 16px;
}

.vehicle-image {
  max-width: 100%;
  max-height: 360px;
  object-fit: contain;
  background: #f6f7f9;
}

.change-btn {
  position: absolute;
  bottom: 5px;
  right: 50%;
  transform: translateX(50%);
  padding: 6px 10px;
  border: none;
  background: rgba(22, 119, 255, .9);
  color: #fff;
  border-radius: 8px;
  font-size: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, .15);
}

.file-input {
  display: none;
}

.info-section {
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, .04);
}

.row {
  display: flex;
  justify-content: space-between;
  padding: 8px 2px;
  font-size: 14px;
}

.label {
  color: #666;
}

.value {
  color: #222;
}

.details-section {
  margin-top: 16px;
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, .04);
}

.section-title {
  font-weight: 600;
  margin-bottom: 10px;
  font-size: 15px;
}

.details-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 10px;
}

.detail-item {
  background: #fafafa;
  border-radius: 10px;
  padding: 10px;
}

.detail-label {
  color: #666;
  font-size: 12px;
}

.detail-value {
  color: #222;
  font-size: 14px;
  margin-top: 4px;
}

.upload-section {
  margin-top: 16px;
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, .04);
}

.upload-section.minimal {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.upload-title {
  font-weight: 600;
  margin-bottom: 8px;
}

.upload-btn {
  margin-top: 8px;
  padding: 5px 12px;
  border: none;
  background: #1677ff;
  color: #fff;
  border-radius: 8px;
}

.upload-btn:disabled {
  opacity: .6;
}

.tip {
  width: 80%;
  color: #888;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 12px;
  margin-top: 6px;
}
</style>
